using System;
using System.Collections.Generic;
using System.Text;
using VSSDKAssist.Assets.Actions.Base;
using Microsoft.Practices.RecipeFramework;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using System.Globalization;

namespace VSSDKAssist.Assets.Actions.VisualStudio
{
	/// <summary>
	/// Action that compiles a Project
	/// </summary>
	public class CompileProjectAction : ActionBase
	{
		private Project project;

		/// <summary>
		/// Gets or sets the project.
		/// </summary>
		/// <value>The project.</value>
		[Input(Required = true)]
		public Project Project
		{
			get { return project; }
			set { project = value; }
		}

		private bool throwException;

		/// <summary>
		/// Gets or sets a value indicating whether [throw exception].
		/// </summary>
		/// <value><c>true</c> if [throw exception]; otherwise, <c>false</c>.</value>
		[Input(Required = false)]
		public bool ThrowException
		{
			get { return throwException; }
			set { throwException = value; }
		}

		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			VisualStudio.ExecuteCommand("Build.BuildSelection", String.Empty);

			// The command is executed asynchronously, wait until the build is done
			while(VisualStudio.Solution.SolutionBuild.BuildState != vsBuildState.vsBuildStateDone)
			{
				Application.DoEvents();
			}

			if(VisualStudio.Solution.SolutionBuild.LastBuildInfo != 0)
			{
				((DTE2)VisualStudio).ToolWindows.ErrorList.Parent.Activate();

				if(this.throwException)
				{
					throw new ActionExecutionException(String.Format(
						CultureInfo.CurrentCulture,
						Properties.Resources.CompilationFailed,
						VisualStudio.Solution.SolutionBuild.LastBuildInfo));
				}
			}
		}
	}
}